<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Connect MetaMask</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 600px;
      margin: 50px auto;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      background: white;
      padding: 30px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    button {
      background-color: #f6851b;
      color: white;
      border: none;
      padding: 12px 24px;
      border-radius: 6px;
      cursor: pointer;
      margin: 5px;
      font-size: 16px;
    }
    button:hover {
      background-color: #e2761b;
    }
    button:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }
    .info {
      margin: 20px 0;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 6px;
      border-left: 4px solid #f6851b;
    }
    .network-selector {
      margin: 20px 0;
    }
    select {
      padding: 8px 12px;
      border-radius: 4px;
      border: 1px solid #ddd;
      margin: 5px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>MetaMask 连接示例</h1>
    
    <button id="connectButton">连接钱包</button>
    <button id="disconnectButton" disabled>断开连接</button>
    
    <div class="info">
      <p><strong>状态:</strong> <span id="status">未连接</span></p>
      <p><strong>地址:</strong> <span id="address">-</span></p>
      <p><strong>网络:</strong> <span id="network">-</span></p>
      <p><strong>链ID:</strong> <span id="chainId">-</span></p>
    </div>

    <div class="network-selector">
      <label for="networkSelect">切换到网络:</label>
      <select id="networkSelect" disabled>
        <option value="">选择网络</option>
        <option value="0x1">Ethereum Mainnet</option>
        <option value="0xaa36a7">Sepolia Testnet</option>
        <option value="0x5">Goerli (deprecated)</option>
        <option value="0x89">Polygon</option>
        <option value="0x38">BNB Smart Chain</option>
        <option value="0xa4b1">Arbitrum One</option>
        <option value="0x2105">Base</option>
      </select>
      <button id="switchNetworkButton" disabled>切换网络</button>
    </div>
  </div>

  <!-- 引入 ethers.js（轻量且易用） -->
  <script src="js/ethers.umd.min.js"></script>

  <script>
    // 检查是否安装了 MetaMask
    if (typeof window.ethereum === 'undefined') {
      document.getElementById('status').textContent = '请安装 MetaMask';
    }

    const connectButton = document.getElementById('connectButton');
    const disconnectButton = document.getElementById('disconnectButton');
    const status = document.getElementById('status');
    const address = document.getElementById('address');
    const network = document.getElementById('network');
    const chainId = document.getElementById('chainId');
    const networkSelect = document.getElementById('networkSelect');
    const switchNetworkButton = document.getElementById('switchNetworkButton');

    let provider = null;
    let signer = null;
    let isConnected = false;

    // 网络名称映射
    const networkNames = {
      '0x1': 'Ethereum Mainnet',
      '0xaa36a7': 'Sepolia Testnet',
      '0x5': 'Goerli (deprecated)',
      '0x89': 'Polygon',
      '0x38': 'BNB Smart Chain',
      '0xa4b1': 'Arbitrum One',
      '0x2105': 'Base'
    };

    // 更新UI状态
    function updateUI() {
      if (isConnected) {
        connectButton.disabled = true;
        disconnectButton.disabled = false;
        networkSelect.disabled = false;
        switchNetworkButton.disabled = false;
      } else {
        connectButton.disabled = false;
        disconnectButton.disabled = true;
        networkSelect.disabled = true;
        switchNetworkButton.disabled = true;
        address.textContent = '-';
        network.textContent = '-';
        chainId.textContent = '-';
      }
    }

    // 获取当前网络信息
    async function getNetworkInfo() {
      try {
        const chainIdValue = await window.ethereum.request({ method: 'eth_chainId' });
        const networkName = networkNames[chainIdValue] || `Unknown (${chainIdValue})`;
        
        document.getElementById('chainId').textContent = chainIdValue;
        document.getElementById('network').textContent = networkName;
        
        // 更新网络选择器
        networkSelect.value = chainIdValue;
        
        return { chainId: chainIdValue, networkName };
      } catch (err) {
        console.error('获取网络信息失败:', err);
        return null;
      }
    }

    // 连接钱包
    connectButton.onclick = async () => {
      try {
        provider = new ethers.providers.Web3Provider(window.ethereum);
        
        // 请求账户连接
        await provider.send("eth_requestAccounts", []);
        
        // 获取签名者
        signer = provider.getSigner();
        
        // 获取地址
        const addressValue = await signer.getAddress();
        
        // 获取网络信息
        const networkInfo = await getNetworkInfo();
        
        // 更新UI
        address.textContent = addressValue;
        status.textContent = '已连接';
        isConnected = true;
        updateUI();
        
        console.log('连接成功:', { address: addressValue, network: networkInfo });
        
      } catch (err) {
        if (err.code === 4001) {
          status.textContent = '用户拒绝连接';
        } else {
          status.textContent = '连接失败';
          console.error('连接失败:', err);
        }
      }
    };

    // 断开连接
    disconnectButton.onclick = () => {
      provider = null;
      signer = null;
      isConnected = false;
      status.textContent = '未连接';
      updateUI();
    };

    // 切换网络
    switchNetworkButton.onclick = async () => {
      const selectedChainId = networkSelect.value;
      if (!selectedChainId) {
        alert('请选择一个网络');
        return;
      }

      try {
        await window.ethereum.request({
          method: 'wallet_switchEthereumChain',
          params: [{ chainId: selectedChainId }],
        });
        
        // 更新网络信息
        await getNetworkInfo();
        
      } catch (err) {
        if (err.code === 4902) {
          // 网络未添加，尝试添加网络
          alert('该网络未添加到MetaMask，请手动添加');
        } else {
          console.error('切换网络失败:', err);
          alert('切换网络失败: ' + err.message);
        }
      }
    };

    // 监听网络变化
    if (window.ethereum) {
      window.ethereum.on('chainChanged', (chainId) => {
        console.log('网络已切换:', chainId);
        getNetworkInfo();
      });

      window.ethereum.on('accountsChanged', (accounts) => {
        console.log('账户已切换:', accounts);
        if (accounts.length === 0) {
          // 用户断开连接
          disconnectButton.click();
        } else if (isConnected) {
          // 用户切换账户
          address.textContent = accounts[0];
        }
      });
    }

    // 初始化UI
    updateUI();
  </script>

</body>
</html>